package com.yxsk.relay.job.admin.core.router;

import com.yxsk.relay.job.admin.core.router.callback.StewardCallback;
import com.yxsk.relay.job.admin.core.router.container.EndpointCycleList;
import com.yxsk.relay.job.admin.core.router.endpoint.EndpointRouterInfo;
import com.yxsk.relay.job.component.admin.registry.Steward;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 11376
 * @CreaTime 2019/6/15 11:59
 * @Description 自动更新服务列表的路由
 */
public abstract class AutoUpdateRouter implements Router {

    // key: appName, value: endpoint list
    protected Map<String, EndpointCycleList> endpointInfoMap;

    private Steward steward;

    protected AutoUpdateRouter(Steward steward) {
        Assert.notNull(steward, "服务管理器不能为空");
        this.endpointInfoMap = new ConcurrentHashMap<>();
        callSteward(steward);
    }

    protected void callSteward(Steward steward) {
        if (this.steward == steward) {
            return;
        }
        steward.addChangeCallback(new StewardCallback(this.endpointInfoMap));
        this.steward = steward;
    }

    protected List<EndpointRouterInfo> getEndpointList(String name) {
        EndpointCycleList list = this.endpointInfoMap.get(name);
        return list == null ? new ArrayList<>() : list.getList();
    }

}
